var switchButton = null;
var additionalStylesEnabled = false;

var ENABLE_ALTERNATE_STYLES = "Включить стиль для слабовидящих";
var DISABLE_ALTERNATE_STYLES = "Отключить стиль для слабовидящих";

var NORMAL_CLASS_NAME = "normal";
var BIG_FONT_CLASS_NAME = "big_font";

var bodyElement = null;
var userInfoContentsContainer = null;
var preloaderBlock = null;
var timeoutHandler = null;


function getXmlHttp()
{
    var xmlHttp = null;
    try
    {
        xmlHttp = new ActiveXObject("Msxml2.HTTP");
    }
    catch(err)
    {
        try
        {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(err)
        {
            xmlHttp = false;
        }
    }
    if(!xmlHttp || typeof(xmlHttp) == "undefined")
    {
        xmlHttp = new XMLHttpRequest();
    }
    return xmlHttp;
}

function onSwitchStylesButtonClick()
{
    additionalStylesEnabled = !additionalStylesEnabled;
    if (additionalStylesEnabled)
    {
        switchButton.value = DISABLE_ALTERNATE_STYLES;
        bodyElement.className = BIG_FONT_CLASS_NAME;
    }
    else
    {
        switchButton.value = ENABLE_ALTERNATE_STYLES;
        bodyElement.className = NORMAL_CLASS_NAME;
    }
}

function onFormSubmit()
{
    var dataToSubmit = {};
    dataToSubmit['name'] = document.getElementById('nameField').value;
    dataToSubmit['sex'] = document.getElementById('sexField').value;
    var notify = document.getElementById('notifyField').checked;
    dataToSubmit['notify'] = (notify) ? 1 : 0;
    dataToSubmit['comment'] = document.getElementById('commentField').value;
    updateUserInfoTable(dataToSubmit);
    return false;
}

function prepareUserInfoTableContents(usersInfo)
{
    var userInfoTableString = '';
    for (var i in usersInfo)
    {
        var userInfo = usersInfo[i];
        userInfoTableString += '<tr>';
        userInfoTableString += '<td>' + userInfo['name'] + '</td>';
        var sexString = (userInfo['sex'] == 0) ? 'Мужской' : 'Женский';
        userInfoTableString += '<td>' + sexString + '</td>';
        var notifyString = (userInfo['notify']) ? 'Уведомить' : 'Не уведомлять';
        userInfoTableString += '<td>' + notifyString + '</td>';
        userInfoTableString += '<td>' + userInfo['comment'] + '</td>';
        userInfoTableString += '<td><a tabindex="' + userInfo['id'] + '" href="javascript:void(0)" title="Удалить">Удалить запись</a></td></tr>';
    }
    return userInfoTableString;
}

function onDeleteLinkClick(event)
{
    var deletedItemId = event.target.tabIndex;
    updateUserInfoTable({id: deletedItemId});
    return false;
}

function updateUserInfoTable(data)
{
    if (!data)
    {
        data = {};
    }
    var req = getXmlHttp();
    req.onreadystatechange = function()
    {
        if (req.readyState == 4 && req.status == 200)
        {
            if (req.responseText != '')
            {
                var usersInfo = eval(req.responseText);
                userInfoContentsContainer.innerHTML = prepareUserInfoTableContents(usersInfo);
                var deleteLinks = userInfoContentsContainer.getElementsByTagName('a');
                for (var i in deleteLinks)
                {
                    deleteLinks[i].onclick = onDeleteLinkClick;
                }
            }
            hidePreloader();
        }
    };
    req.open("POST", "/lab2/user_info_management.php", true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var preparedData = '';
    for (var key in data)
    {
        if (data.hasOwnProperty(key))
        {
            preparedData += key + '=' + data[key] + '&';
        }
    }
    if (preparedData.length > 0)
    {
        preparedData = preparedData.substr(0, preparedData.length - 1);
    }
    req.send(preparedData);
    showPreloader();

    if (timeoutHandler !== null)
    {
        clearTimeout(timeoutHandler);
    }
    setTimeout(updateUserInfoTable, 8000);
}

function hidePreloader()
{
    preloaderBlock.style = "display: none;";
}

function showPreloader()
{
    preloaderBlock.style = "display: block;";
}

window.onload = function()
{
    bodyElement = document.getElementById('body');
    userInfoContentsContainer = document.getElementById('userInfoContents');
    preloaderBlock = document.getElementById('pleloaderBlock');

    var mainForm = document.getElementById('mainForm');
    mainForm.onsubmit = onFormSubmit;
    switchButton = document.getElementById('switchStylesButton');
    switchButton.onclick = onSwitchStylesButtonClick;

    updateUserInfoTable();
};
